home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c++-part1 / 415 < prev    next >
Encoding:
Text File  |  1996-08-05  |  1.5 KB  |  49 lines

  1. Newsgroups: comp.lang.c++
  2. Path: artemis.sto.fdata.se!news
  3. From: Niklas Mellin <niklas.mellin@sto.fdata.se>
  4. Subject: Re: beginner question - typecasting
  5. Sender: news@artemis.sto.fdata.se (UseNet NetNews)
  6. Message-ID: <30EBCED7.774@sto.fdata.se>
  7. Date: Thu, 4 Jan 1996 12:57:59 GMT
  8. Content-Transfer-Encoding: 7bit
  9. Content-Type: text/plain; charset=us-ascii
  10. References: <4cei1r$s02@sun.cis.smu.edu>
  11. Mime-Version: 1.0
  12. X-Mailer: Mozilla 2.0b4 (WinNT; I)
  13. Organization: WM-data F÷rsvarsdata AB, Sweden
  14.  
  15. Damon Bowman wrote:
  16. > When you are typecasting, is there any difference between:
  17. > a = int(x)
  18. > and
  19. > a = (int) x
  20.  
  21. [...]
  22.  
  23. Yes the first is not type casting, but a "type conversion".
  24.  
  25. When x is a  variables of built in types there is no
  26. difference. But if x is a varible of some class for instance
  27. the first form generates a call to that class' operator int(),
  28. generating a compile time error message if there is no such
  29. member function.
  30.  
  31. The 2nd form is an inheritance from plain C, and doesn't work
  32. when x is of class type. It is also
  33. not "safe", meaning that the compiler will not generate error
  34. messages in certain situations, and you will get buggy code
  35. or run time errors instead.
  36.  
  37. In general u should choose the conversion form if possible,
  38. but sometimes a type cast can be handy. One case is if you
  39. are using a 3rd part class library that is not well written
  40. (read MFC) and they forgot to declare function parameters as 
  41. const and you have a const object you would like to pass to
  42. that function. Then you can type cast your object or variable
  43. to non const.
  44.  
  45. ---
  46. Niklas Mellin
  47.